package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.ObjectUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: Liu
 * @date: 2022/02/23
 * @time: 16:16
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    /*static List<String> uris = new ArrayList<>();

    static {
        uris.add("/employee/login");
        uris.add("/employee/logout");
        uris.add("/backend/**");
        uris.add("/front/**");
        uris.add("/user/sendMsg");
        uris.add("/user/login");
    }*/

    public static AntPathMatcher matcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //对象转换
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        //获取请求路径
        String uri = req.getRequestURI();
        //构建白名单
        String[] uris = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login",
                "/pay/qrcode"
        };


        //调用check方法检查路径是否在白名单内
        boolean check = check(uri, uris);
        //在，放行
        if (check) {
            chain.doFilter(req, res);
            return;
        }
        //不在，判断session中有没有登陆
        Object employee = req.getSession().getAttribute("employee");
        System.out.println("uris = " + uris);
        //已登录，放行
        if (!ObjectUtils.isEmpty(employee)) {
            Long empId = (Long) req.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            /*uris.add("/employee/**");
            uris.add("/category/**");
            uris.add("/dish/**");
            uris.add("/setmeal/**");
            uris.add("/order/**");
            req.getSession().removeAttribute("employee");*/
            chain.doFilter(req, res);
            return;
        }
        //4-2、判断登录状态，如果已登录，则直接放行
        if (req.getSession().getAttribute("user") != null) {
            log.info("用户已登录，用户id为：{}", req.getSession().getAttribute("user"));

            Long userId = (Long) req.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            /*uris.add("/user/**");
            uris.add("/dish/**");
            uris.add("/shoppingCart/**");
            uris.add("/addressBook/**");
            uris.add("/order/**");
            req.getSession().removeAttribute("user");*/
            chain.doFilter(req, res);
            return;
        }
        //未登录，拦截
        res.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * @param uri
     * @param uris
     * @return 请求路径是否在白名单内, 在返回true，不在返回false
     */
    private boolean check(String uri, /*List<*/String[]/*>*/ uris) {
        for (String s : uris) {
            boolean match = matcher.match(s, uri);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
